﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace CMS6Tools.Common
{
    public class GenericConfigurationSectionHandler<TConfigurationData> : IConfigurationSectionHandler
        where TConfigurationData : class,new()
    {
        public virtual object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            var configureData = default(TConfigurationData);
            var serializer = new XmlSerializer(typeof(TConfigurationData));
            using (var stringReader = new StringReader(section.OuterXml))
            {
                configureData = serializer.Deserialize(stringReader) as TConfigurationData;
            }
            return configureData;
        }

        public static TConfigurationData Load()
        {
            var xmlRootAttributes = typeof(TConfigurationData).GetCustomAttributes(typeof(XmlRootAttribute),false);
            if (xmlRootAttributes != null && xmlRootAttributes.Count() > 0)
            {
                var sectionName = (xmlRootAttributes[0] as XmlRootAttribute).ElementName;
                return CmsConfigurationManager.GetSection(sectionName) as TConfigurationData;
            }
            return default(TConfigurationData);
        }
    }
}
